package com.atguigu.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * @program: cloud2020
 * @description: 自定义全局过滤器
 * @author: YuWenYi
 * @create: 2021-04-15 22:49
 **/
@Component
@Slf4j
public class GlobalLogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("请求进入GlobalLogFilter -->"+new Date());

        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if (username == null){
            log.warn("警告!!   用户名为null!");
            exchange.getResponse().setStatusCode(HttpStatus.BAD_GATEWAY);
            return exchange.getResponse().setComplete();  //返回错误
        }
        //放行!
        return chain.filter(exchange);
    }

    //加载过滤器的顺序,数字越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
